<template>
    <el-card shadow="hover" class="management-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="学生姓名">
                <el-input v-model="searchForm.studentName" placeholder="请输入学生姓名" clearable />
            </el-form-item>

            <el-form-item label="科目">
                <el-input v-model="searchForm.courseName" placeholder="请输入科目名称" clearable />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="header-actions">
            <el-button class="addbutton" type="primary" size="default" @click="showAddScoreDialog">
                <el-icon class="el-icon--left">
                    <Plus />
                </el-icon>
                新增成绩
            </el-button>
            <el-button type="success" @click="importDialogVisible = true">
                <el-icon class="el-icon--left">
                    <Upload />
                </el-icon>
                批量导入
            </el-button>
            <el-link type="primary" :underline="false" @click="downloadFile" style="margin-left: 10px;">
                下载模板
            </el-link>
        </div>

        <!-- 导入成绩对话框 -->
        <el-dialog v-model="importDialogVisible" title="批量导入成绩" width="30%">
            <el-upload class="upload-score" drag :action="uploadUrl" :headers="headers"
                :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
                :show-file-list="false" accept=".xlsx,.xls">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        仅支持.xls/.xlsx格式文件，<el-link type="primary" @click="downloadFile">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
        </el-dialog>

        <el-table :data="tableData" border stripe highlight-current-row style="width: 100%"
            header-row-class-name="custom-header">
            <el-table-column prop="studentName" label="姓名" width="220" />
            <el-table-column prop="studentId" label="学号" width="300" />
            <el-table-column prop="courseName" label="科目" width="287" />
            <el-table-column prop="score" label="成绩" width="150">
                <template #default="{ row }">
                    <span :class="{ 'text-danger': row.score < 60 }">{{ row.score }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250" align="center">
                <template #default="{ row }">
                    <div class="action-buttons">
                        <el-button type="primary" size="small" plain @click="editScore(row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button type="danger" size="small" plain @click="deleteScore(row.id)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
            <el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size="pageSize"
                :current-page="currentPage" @current-change="handlePageChange" @size-change="handleSizeChange"
                class="mt-4" />
        </div>
    </el-card>

    <!-- 成绩编辑对话框 -->
    <el-dialog :title="isEditMode ? '编辑成绩' : '新增成绩'" v-model="dialogVisible" width="40%" @closed="handleDialogClosed">
        <el-form :model="currentScore" :rules="rules" ref="scoreForm" label-width="80px">
            <el-form-item label="学生姓名" prop="studentName">
                <el-input v-model="currentScore.studentName" placeholder="请输入学生姓名" />
            </el-form-item>
            <el-form-item label="学号" prop="studentId">
                <el-input v-model="currentScore.studentId" placeholder="请输入学生学号" />
            </el-form-item>
            <el-form-item label="科目" prop="courseName">
                <el-select v-model="currentScore.courseName" placeholder="请选择科目">
                    <el-option label="数学" value="数学" />
                    <el-option label="语文" value="语文" />
                    <el-option label="英语" value="英语" />
                </el-select>
            </el-form-item>
            <el-form-item label="成绩" prop="score">
                <el-input-number v-model="currentScore.score" :min="0" :max="100" :step="1" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { Plus, Edit, Delete, Upload } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { get } from '@/request/request.js'
import { UploadFilled } from '@element-plus/icons-vue'

// 数据相关
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const currentScoreId = ref(null)

const importDialogVisible = ref(false)
const uploadUrl = ref(`http://localhost:5000/api/importScores`)

// 上传成功处理
const handleUploadSuccess = (response) => {
    if (response.code === 200) {
        ElMessage.success(`导入成功`)
        fetchData(currentPage.value)
        importDialogVisible.value = false
    } else {
        ElMessage.error(response.msg || '导入失败')
    }
}
// 上传失败处理
const handleUploadError = (error) => {
    ElMessage.error(`文件上传失败：${error.message}`)
}
// 文件上传前校验
const beforeUpload = (file) => {
    const isExcel = file.type.includes('excel') ||
        file.name.endsWith('.xlsx') ||
        file.name.endsWith('.xls')
    if (!isExcel) {
        ElMessage.error('只能上传Excel文件!')
        return false
    }
    return true
}

// 对话框相关
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentScore = ref({
    id: null,
    studentName: '',
    studentId: '',
    courseName: '',
    score: 60
})

// 搜索表单
const searchForm = ref({
    studentName: '',
    courseName: '',
})

// 验证规则
const rules = {
    studentName: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
    studentId: [{ required: true, message: '请输入学生学号', trigger: 'blur' }],
    courseName: [{ required: true, message: '请选择科目', trigger: 'change' }],
    score: [{ required: true, message: '请输入成绩', trigger: 'blur' }],
}

// 获取数据
const fetchData = async (page = 1) => {
    try {
        const params = {
            ...searchForm.value,
            page: page,
            pageSize: pageSize.value
        }
        const response = await get('/api/scores', params)
        console.log('Response:', response);
        tableData.value = response.data.list
        total.value = response.data.total
    } catch (error) {
        ElMessage.error('获取成绩列表失败')
        console.error('Error:', error)
    }
}

// 搜索处理
const handleSearch = () => {
    currentPage.value = 1
    fetchData()
}

// 重置搜索
const handleReset = () => {
    searchForm.value.studentName = ''
    searchForm.value.courseName = ''
    handleSearch()
}

// 分页处理
const handlePageChange = (page) => {
    currentPage.value = page
    fetchData(page)
}

// 每页显示数量变化
const handleSizeChange = (size) => {
    pageSize.value = size
    fetchData()
}

//下载模板
const downloadFile = () => {
    const link = document.createElement('a');
    link.href = 'https://jobsystem.oss-cn-beijing.aliyuncs.com/%E6%88%90%E7%BB%A9%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx'
    link.click();
    link.remove();
}

//删除成绩
const deleteScore = async (id) => {
    try {
        await ElMessageBox.confirm('此操作将永久删除该成绩, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await get(`/api/deleteScore/${id}`)
        ElMessage.success('删除成功')
        fetchData(currentPage.value)
    } catch (error) {
        ElMessage.error('删除失败')
        console.error('Error:', error)
    }
}

//编辑通知
const editScore = (score) => {
    currentScore.value = { ...score }
    dialogVisible.value = true
    isEditMode.value = true
    currentScoreId.value = score.id
}

//新增成绩
const showAddScoreDialog = () => {
    dialogVisible.value = true
    isEditMode.value = false
}

//提交表单
const handleSubmit=async()=>{
    try{
        const scoreData= {...currentScore.value}
        if(isEditMode.value){
            scoreData.id=currentScoreId.value
            await get('/api/updateScore',scoreData)
            ElMessage.success('成绩更新成功')
        }else{
            await get('/api/addScore',scoreData)
            ElMessage.success('成绩添加成功')
        }
        dialogVisible.value=false
        fetchData(currentPage.value)
    }catch(error){
        ElMessage.error(isEditMode.value?'更新失败':'添加失败')
        console.error('Error:',error)
    }
}

//重置表单
const handleDialogClosed = () => {
    currentScore.value = {
        id: null,
        studentName: '',
        studentId: '',
        courseName: '',
        score: 60
    }
}

onMounted(() => {
    fetchData()
})
</script>

<style lang="scss" scoped>
.text-danger {
    color: #f56c6c;
    font-weight: bold;
}

.management-card {
    margin: 0px;
}

.search-form {
    padding: 0px;
}

.header-actions {
    padding: 0px;
}

.action-buttons {
    display: flex;
    justify-content: center;
    gap: 8px;
}

.pagination-wrapper {
    padding-top: 8px;
    display: flex;
    justify-content: flex-end;
}
</style>